package com.xiaoyu.izf.aspect;

import com.xiaoyu.izf.config.SysConfig;
import com.xiaoyu.izf.exception.CustomException;
import com.xiaoyu.izf.model.exception.BusinessStatusEnum;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Aspect
@Component
public class RequestAspect {

    @Before("@annotation(com.xiaoyu.izf.annotation.RequestAuth)")
    public void before(JoinPoint joinPoint) {

        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        HttpSession session = request.getSession();

        if (session.getAttribute(SysConfig.user_info_in_session_key) != null) {
            request.setAttribute("user", session.getAttribute(SysConfig.user_info_in_session_key));
            return;
        }
        throw new CustomException(BusinessStatusEnum.NOT_LOGIN);

        //未登录
//        UserInfo user = (UserInfo) session.getAttribute(SysConfig.user_info_in_session_key);
//        if (user == null) {
//            throw new CustomException(BusinessStatusEnum.NOT_LOGIN);
//        }
//
//        //权限
//         RequestAuth requestAuth = ((MethodSignature)joinPoint.getSignature()).getMethod().getAnnotation(RequestAuth.class);
//        String admin = requestAuth.role();
//        String[] vipTypes = requestAuth.vipTypes();
//        //要求admin
//        if ("admin".equalsIgnoreCase(admin)&&user.getIsAdmin()==0){
//            throw new CustomException(BusinessStatusEnum.NO_PERMISSION);
//        //要求vipType
//        }else if (vipTypes.length>0){
//            boolean find = false;
//            for (int i=0;i<vipTypes.length;i++){
//                if (vipTypes[i].equals(user.getVipType()+"")){
//                    find = true;
//                    break;
//                }
//            }
//            if (!find){
//                throw new CustomException(BusinessStatusEnum.NO_PERMISSION);
//            }
//        }
//
//        request.setAttribute("user", session.getAttribute(SysConfig.user_info_in_session_key));
    }
}
